/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.core.ContentDocument;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.persistence.exception.DeleteException;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.VirtualFolderForm;
import com.blandware.atleap.webapp.util.core.LinkedObjectsInfoContainer;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>Deletes content resource folder.
 * </p>
 * <p><a href="DeleteContentResourceFolderAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.8 $ $Date: 2007/12/18 18:11:46 $
 * @struts.action path="/core/contentResource/deleteFolder"
 * name="virtualFolderForm"
 * scope="request"
 * validate="false"
 * roles="core-contentResource-delete"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="viewLinkedObjects"
 * path="/core/linkedObjects/view.do"
 */
public final class DeleteContentResourceFolderAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        VirtualFolderForm virtualFolderForm = (VirtualFolderForm) form;
		String path;
		if ( !GenericValidator.isBlankOrNull(virtualFolderForm.getPath()) ) {
			path = virtualFolderForm.getPath();
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing path. Returning to list...");
			}
            return mapping.findForward("listContentResources");
		}

        String initialPath = path;

        if ( path == null || path.equals("/") ) {
			path = "";
		}

		// ensure, that current folder starts with slash and does not end with slash
		if ( path.length() > 0 ) {
			if ( !path.startsWith("/") ) {
				path = "/" + path;
			}
			if ( path.endsWith("/") ) {
				path = path.substring(0, path.length() - 1);
			}
		}

		// get all content resources, which exist in given folder
        String whereClause = "r.uri like '" + StringUtil.sqlEscape(Constants.RESOURCES_URI_PREFIX + path + "/") + "%'";
        QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(whereClause);

        ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
        PartialCollection contentResources = contentResourceManager.listContentResources(queryInfo);

		if (contentResources.isEmpty()) {
			// content resources not found. they might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("virtualFolderIsEmpty", new ActionMessage("core.virtialFolder.errors.empty"));
			saveErrors(request, errors);
            return mapping.findForward("listContentResources");
		}

        // collecting IDs of used resources
        List usedResourcesIds = new ArrayList();
        for (Iterator i = contentResources.iterator(); i.hasNext(); ) {
            ContentResource contentResource = (ContentResource) i.next();
            if (contentResource.isInUse()) {
                usedResourcesIds.add(contentResource.getId());
            }
        }

        if ( !"true".equalsIgnoreCase(request.getParameter("force")) && !usedResourcesIds.isEmpty() ) {
			// trying to delete used resources - display warning
            String action = mapping.findForward("listContentResources").getPath();
            String redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
			ActionMessages messages = new ActionMessages();
			messages.add("deleteWarning", new ActionMessage("core.contentResource.messages.folderDeleteWarning"));
			saveMessages(request, messages);

            LinkedObjectsInfoContainer container = new LinkedObjectsInfoContainer();
            container.setRedirectUrl(redirectUrl);
            container.setPath(initialPath);
            container.setDeleteAction(mapping.getPath());
            container.setObjectsIds(usedResourcesIds);
            container.setObjectType(LinkedObjectsInfoContainer.TYPE_RESOURCE);
            session.setAttribute(WebappConstants.LINKED_OBJECTS_INFO_CONTAINER_KEY, container);

            saveToken(request);
			return mapping.findForward("viewLinkedObjects");
		}

        CacheUtil cacheUtil = CacheUtil.getInstance(request);
        SearchManager searchManager = SearchManager.getInstance(servlet.getServletContext());

        // whether some resources could not be deleted
        boolean someWereNotDeleted = false;

        // really delete resources
        for (Iterator i = contentResources.iterator(); i.hasNext(); ) {
            ContentResource contentResource = (ContentResource) i.next();
            String uri = contentResource.getUri();

            try {
                contentResourceManager.deleteContentResource(contentResource.getId());

                //flush cache
                cacheUtil.flushResourceCache(uri);

                //index
                if ( contentResource instanceof ContentDocument ) {
                    searchManager.unIndexDocument(uri, request);
                }
            } catch ( DeleteException e ) {
                someWereNotDeleted = true;
            }
        }

        if (someWereNotDeleted) {
            saveToken(request);
            ActionMessages errors = new ActionMessages();
            errors.add("contentResourceCannotDelete", new ActionMessage("errors.contentResourceCannotDelete"));
            saveErrors(request, errors);
            return mapping.findForward("listContentResources");
        }

        return mapping.findForward("listContentResources");
	}
}